#include "base.h"
#include "bit_file.h"

#include <sys/stat.h>

void bit_file_init(bit_file * bf, FILE * fp) {
	struct stat st;
	fstat(fp->_file, &st);
	bf->len = st.st_size;
	bf->bytes = malloc(st.st_size);
	bf->off = 0;
	fread(bf->bytes, st.st_size, sizeof(char), fp);
}

void bit_file_free(bit_file * bf) {
	free(bf->bytes);
	bf->bytes = NULL;
}

int bit_file_peek_bits(bit_file * bf, int bits) {
	assert(bits < 32);
	return bf->bytes[bf->off] & ((1<<(bits+1))-1);
}

int bit_file_read(bit_file * bf, int bytes, void *out) {
	int cnt = bf->len - bf->off;
	cnt = cnt < bytes ? cnt : bytes;
	memcpy(out, bf->bytes, cnt);
	return cnt;
}



